package calculator;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Aservlet extends HttpServlet {


	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		/*System.out.println(textvalue);*/
		/*System.out.println(12+9*3);*/
		
		String textvalue = request.getParameter("count");
		String copy=textvalue;
		String last = textvalue.substring(copy.length()-1);
		ScriptEngine jse=new ScriptEngineManager().getEngineByName("JavaScript");
		//验证规则
		/*String reg="/^[0-9]*$/";*/
		String reg="[0-9]{1,}";
		//编译正则表达式
		Pattern pattern = Pattern.compile(reg);
		/*System.out.println(pattern.matcher(last).matches());*/
		try {
			//判断最后一个数字是否为数字
			if(pattern.matcher(last).matches()){
					/*System.out.println(textvalue);*/
					Object result=jse.eval(textvalue);
					request.setAttribute("result", result);
					request.getRequestDispatcher("/calculator.jsp").forward(request, response);;
			}else{
				textvalue=textvalue.substring(0, textvalue.length()-1);
					Object result=jse.eval(textvalue);
					/*System.out.println(result);*/
					request.setAttribute("result", result);
					request.getRequestDispatcher("/calculator.jsp").forward(request, response);;
			}
		} catch (ScriptException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
			/*Matcher matcher = pattern.matcher(last);*/
			
		}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request,response);
	}


}
